package com.dongdongshop.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.Enum.ResultEnum;
import com.dongdongshop.core.SpecificPrint;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.TbUserServiceI;
import com.dongdongshop.util.ShiroUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;

@Controller
@RequestMapping("userController")
public class UserController {
    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private TbUserServiceI tbUserServiceI;

    //mq发送验证码
    @RequestMapping("getCode")
    @ResponseBody
    public SpecificPrint getCode(String phone){
    //    System.err.println(phone);
        try {
            rocketMQTemplate.convertAndSend("CCTV8",phone);
            return SpecificPrint.response(ResultEnum.SENDASUCCESS);
        }catch (Exception e){
            logger.error(ResultEnum.ERROR.getMessage(),e);
            return SpecificPrint.response(ResultEnum.ERROR);
        }
    }

    //注册
    @RequestMapping("saveTbuser")
    @ResponseBody
    public SpecificPrint saveTbuser(TbUser tbUser, String pwd, String Verification){//前台传来Verification验证码
            try {
                String key = "phoneNumber"; //phoneNumber手机号
                String yzm = (String) redisTemplate.boundHashOps(key).get(tbUser.getPhone()); // 内部验证码
                if(tbUser.getPassword().equals(pwd) && yzm.equals(Verification) && !"".equals(tbUser.getPassword()) && !"".equals(pwd)){
                    String salt = ShiroUtils.generateSalt(6);//获取盐，加密用的key
                    String md5 = ShiroUtils.encryptPassword("MD5", tbUser.getPassword(), salt, 10);
                    tbUser.setSalt(salt);
                    tbUser.setPassword(md5);
                    tbUser.setStatus("1");
                    tbUser.setCreated(new Date());
                    tbUser.setUpdated(new Date());
                    tbUserServiceI.saveTbuser(tbUser);
                    return SpecificPrint.response(ResultEnum.SUCCESS);
                }else {
                    return SpecificPrint.response(ResultEnum.ERROR);
                }

            }catch (Exception e){
                logger.error(ResultEnum.ERROR.getMessage(),e);
                return SpecificPrint.response(ResultEnum.ERROR);
            }
    }
}
